package cn.edu.xmist.supermarketsys.controller;

import cn.edu.xmist.supermarketsys.Util.ObjtoLayJson;
import cn.edu.xmist.supermarketsys.Util.Strs;
import cn.edu.xmist.supermarketsys.entity.Product;
import cn.edu.xmist.supermarketsys.entity.Supplier;
import cn.edu.xmist.supermarketsys.service.ProductService;
import cn.edu.xmist.supermarketsys.service.SupplierService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/supplier")
public class SupplierController {
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private ProductService wareService;

    public static String[] columns = {"id", "supplierCode", "supplierName", "supplierBrand"};

    @RequestMapping("/list")
    public String list(Integer page, Integer limit) throws Exception {
        List<Supplier> list = supplierService.list();
        return ObjtoLayJson.ListtoJson(list, columns);
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Supplier supplier) {
        if (supplier.getId() == null) {
            QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("supplier_code", supplier.getSupplierCode());
            List<Supplier> list = supplierService.list(queryWrapper);
            if (list.size() > 0) {
                return Strs.FAIL_RETURN_JSON;
            }
        }
        Boolean flag = supplierService.saveOrUpdate(supplier);
        return Strs.SUCCESS_RETURN_JSON;
    }

    @RequestMapping("/deleteById")
    public String deleteById(Long id) {
        Supplier supplier = supplierService.getById(id);
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_code", supplier.getSupplierCode());
        List<Product> list = wareService.list(queryWrapper);
        if (list.size() > 0) {
            return Strs.FAIL_RETURN_JSON;
        }
        Boolean flag = supplierService.removeById(id);
        return Strs.SUCCESS_RETURN_JSON;
    }

}
